package org.example.novel.web;

import cn.hutool.core.util.IdUtil;
import com.wf.captcha.ArithmeticCaptcha;
import org.example.novel.annotation.Anonymous;
import org.example.novel.domain.requ.LoginUser;
import org.example.novel.service.AuthService;
import org.example.novel.utlis.RedisUtils;
import org.example.novel.utlis.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static org.example.novel.constant.AuthConstant.*;

@RestController
@RequestMapping(AUTH_API)
public class AuthController {

    @Autowired
    AuthService authService;

    @Autowired
    RedisUtils redisUtils;

    @Anonymous
    @PostMapping(LOGIN)
    public Result<String> token(@RequestBody LoginUser loginUser) {

        authService.verifyCaptcha(loginUser.getKey(), loginUser.getCode());

        String token = authService.token(loginUser.getUsername(), loginUser.getPassword());

        return Result.success(token);
    }

    @Anonymous
    @GetMapping(CAPTCHA)
    public Result<Map<String, Object>> getCaptcha() {
        //生成唯一ID
        String snowflakeNextIdStr = IdUtil.getSnowflakeNextIdStr();
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);


        String imgBase = captcha.toBase64();

        redisUtils.setStr(CAPTCHA_PREFIX + snowflakeNextIdStr, captcha.text(), 5, TimeUnit.MINUTES);

        HashMap<String, Object> captchaMap = new HashMap<>();
        captchaMap.put(KEY, snowflakeNextIdStr);
        captchaMap.put(IMG_BASE, imgBase);

        return Result.success(captchaMap);
    }


}
